package com.tanhua.sso.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.io.IOException;


@Slf4j
public class SendMsgUtils {


    public static String sendSms(String mobile) throws IOException {

        AliyunSMSConfig aliyunSMSConfig = new AliyunSMSConfig();

//        //类加载器加载配置文件
//        InputStream resourceAsStream = SendMsgUtils.class.getClassLoader().getResourceAsStream("aliyun.properties");
//        Properties properties = new Properties();
//        properties.load(resourceAsStream);

        DefaultProfile profile = DefaultProfile.getProfile(aliyunSMSConfig.getRegionId(),
                aliyunSMSConfig.getAccessKeyId(), aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        //设置验证码
        String code = RandomUtils.nextInt(100000,999999)+"";

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", "15162675162"); //目标手机号
        request.putQueryParameter("SignName", aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":"+code+"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (data!=null && data.contains("Message:OK")){
                log.info("发送短信验证码成功~ data = " + data);
                //返回数据包含Message:OK则返回验证码
                return code;
            }

            //{"Message":"OK","RequestId":"EC2D4C9A-0EAC-4213-BE45-CE6176E1DF23","BizId":"110903802851113360^0","Code":"OK"}
            //System.out.println(response.getData());
        } catch (Exception e) {
            log.error("发送短信验证码失败~");
        }
        return null;
    }
}
